package io.qifan.desktop.client.state;

import io.qifan.desktop.api.protocol.BaseMessage;
import io.qifan.desktop.api.protocol.request.ConnectReqMsg;
import io.qifan.desktop.api.protocol.response.ConnectRespMsg;
import io.qifan.desktop.client.socket.AsyncWriter;
import io.qifan.desktop.client.socket.SocketUtils;
import io.qifan.desktop.client.store.token.TokenStore;
import io.qifan.desktop.common.constants.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component(OrderState.ONLINE)
@Slf4j
public class SpareState extends AbstractOrderState {
    @Autowired
    TokenStore tokenStore;
    @Autowired
    AsyncWriter<ConnectReqMsg, ConnectRespMsg> asyncWriter;

    @Override
    protected void connect0(ConnectReqMsg connectReqMsg) {
        log.info("发起连接请求：{}", connectReqMsg.toString());
        SocketUtils.stompSession.send(SocketUtils.createHeader("/socket/desktop/connect/request"),
                connectReqMsg);
        ConnectRespMsg baseMessage = asyncWriter.writeAndGet(connectReqMsg);
    }

    @EventListener(ConnectRespMsg.class)
    public void connectResponse(ConnectRespMsg respMsg) {
        log.info("对方连接响应结果：{}", respMsg);
        asyncWriter.complete(respMsg);
    }

    @Override
    protected void receiveConnect0(ConnectReqMsg connectReqMsg) {
        log.info("收到对方连接请求：{}", connectReqMsg.toString());
        // TODO 如何响应
        ConnectRespMsg connectRespMsg = new ConnectRespMsg();
        connectRespMsg.setUuid(connectRespMsg.getUuid());
        connectRespMsg.setCode(ResultCode.Success.getCode());
        connectRespMsg.setIsSuccess(true);
        SocketUtils.send("/socket/desktop/response", connectRespMsg);
    }
}
